

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:video_player/video_player.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/video/ShortVideoBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/event/BottomNavigationBarIndex.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SmartRefresherHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/main.dart';
import '../../AppMain.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/main/video/VideoVM.dart';


// 短视频 推荐
class VideoRecommendedWidget extends StatefulWidget {
  @override
  _VideoRecommendedWidgetState createState() => _VideoRecommendedWidgetState();
}

class _VideoRecommendedWidgetState extends State<VideoRecommendedWidget> with AutomaticKeepAliveClientMixin{

  RefreshController _refreshController=RefreshController();
  PullDataRefresher<ShortVideoBean> _mPullDataRefresher=PullDataRefresher(null);
  late LoadCallback _loadCallback;

  VideoVM _videoVM=VideoVM();

  @override
  void initState() {
    super.initState();
    _loadCallback=(pullbean){
       _videoVM.getShortVideoList(pullbean,isDialog: false,requestDone: (){
         _mPullDataRefresher.onRefresher(_videoVM.videoList);
       });
    };
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black87,
      child: SmartRefresherWidget(
        onLoading: _loadCallback,
        onRefresh: _loadCallback,
        // enablePullUp: true,
        // enablePullDown: true,
        loadBuild: (BuildContext context, List<ShortVideoBean> result) {
           return result.isEmpty?Empty():PageView.builder(
             scrollDirection:Axis.vertical,
             itemCount: result.length,
             itemBuilder: (context,index){
               return PageItem(result[index]);
             },);
        },
        controller:_refreshController ,
        valueNotifier: _mPullDataRefresher,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class PageItem extends StatefulWidget {

  ShortVideoBean shortVideoBean;

  PageItem(this.shortVideoBean);

  @override
  _PageItemState createState() => _PageItemState();
}

class _PageItemState extends State<PageItem> {
  @override
  Widget build(BuildContext context) {
    var scheight = MediaQuery.of(context).size.height;
    var scwidth = MediaQuery.of(context).size.width;
    return Container(
      child: Stack(children: [
        PlayWidget(widget.shortVideoBean),
        Container(
          height: double.infinity,
          alignment: Alignment.bottomRight,
          padding: EdgeInsets.fromLTRB(0, 0, 12.sp, scheight/10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 40.sp,
                height: 40.sp,
                margin: EdgeInsets.fromLTRB(0, 0, 0, 30.h),
                child:ClipRRect(
                  // radius: 20.sp,
                  borderRadius: BorderRadius.all(Radius.circular(20.sp)),
                  child: assetImage(widget.shortVideoBean.icon??"",fit: BoxFit.fill,width: 20.sp,height: 20.sp),
                ) ,
              ),
              FindFunWidget("喜欢", widget.shortVideoBean.isLike==1?"ic_find_comment_like_yes.png":"ic_find_comment_like_no.png"),
              FindFunWidget("评价", "ic_find_comment.png"),
              FindFunWidget("分享", "ic_find_share.png"),
              Visibility(
                visible: (widget.shortVideoBean.sameProductCount??0)>0,
                child: Container(
                  width: 40.sp,
                  margin: EdgeInsets.fromLTRB(0, 10.h, 0, 0),
                  alignment: Alignment.bottomCenter,
                  child:Stack(
                    alignment: Alignment.bottomCenter,
                    children: [
                      Image.asset(assetPath("ic_find_main_gift_bag.png"),width: 40.w,fit: BoxFit.fitWidth,),
                      Container(
                        alignment: Alignment.bottomCenter,
                        padding: EdgeInsets.fromLTRB(0, 0, 0, 2.h),
                        child: Text("${widget.shortVideoBean.sameProductCount??0}",
                          style: TextStyle(fontSize: 12.sp,color: Colors.white),),
                      )
                    ],
                  ) ,
                ),
              ),
            ],
          ),
        ),
        Container(
          alignment: Alignment.bottomLeft,
          margin: EdgeInsets.fromLTRB(16.w, 0, scwidth*2/7, 24.h),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("@${widget.shortVideoBean.nickname}",style: TextStyle(fontSize: 16.sp,color: Colors.white),),
              Padding(padding: EdgeInsets.fromLTRB(0, 10.h, 0, 0)),
              Text("${widget.shortVideoBean.title}",
                overflow:TextOverflow.ellipsis,
                style: TextStyle(fontSize: 14.sp,color: Colors.white,),maxLines: 2,),
            ],
          ),
        )
      ],),
    );
  }
}

class PlayWidget extends StatefulWidget {

  late ShortVideoBean? shortVideoBean;

  PlayWidget(this.shortVideoBean);

  @override
  _PlayWidgetState createState() => _PlayWidgetState();
}

class _PlayWidgetState extends State<PlayWidget> with RouteAware{

  late VideoPlayerController _controller;
  late VoidCallback listener;

  @override
  void initState() {
    super.initState();
    print("object  ${widget.shortVideoBean}");
    if(widget.shortVideoBean?.videoUrl?.isNotEmpty==true){
      _controller = VideoPlayerController.network(
        widget.shortVideoBean?.videoUrl??"",
        videoPlayerOptions: VideoPlayerOptions(mixWithOthers: false),
      );
    }
    eventBus.on<BottomNavigationBarIndex>().listen((event){
      if(event is BottomNavigationBarIndex){
        if (mounted){
          if(event.tabIndex==1){
            _controller.play();
          }else{
            _controller.pause();
          }
        }
      }
    });
    listener=() {
      // print("object 视频变化 _controller");
      WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
        if (mounted){
          setState(() {

          });
        }
      });
    };
    _controller.addListener(listener);
    _controller.setLooping(true);
    _controller.initialize();
  }


  @override
  Widget build(BuildContext context) {
    var scSize = MediaQuery.of(context).size;
    return Container(
      alignment: Alignment.center,
      // child: Image.network(widget.shortVideoBean?.pic??"",alignment: Alignment.center,fit: BoxFit.fitWidth,width: scSize.width,),
      child: _controller.value.isInitialized?VideoPlayer(_controller):Image.network(widget.shortVideoBean?.pic??"",alignment: Alignment.center,fit: BoxFit.fitWidth,width: scSize.width,),
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    if(tabIndex==1){
      _controller.play();
    }
    print("object  didChangeDependencies");
  }

  @override
  void deactivate() {
    super.deactivate();
    routeObserver.unsubscribe(this);
    print("object  deactivate");
    _controller.pause();
  }


  @override
  void didPush() {
    super.didPush();
    _controller.pause();
    // push进入当前页面时走这里
    print('object 生命周期监听 didPush');
  }

  @override
  void didPushNext() {
    super.didPushNext();
    _controller.pause();
    // 当前页面push到其他页面走这里
    print('object 生命周期监听 didPushNext');
  }

  @override
  void didPop() {
    super.didPop();
    // pop出当前页面时走这里
    if(tabIndex==1){
      _controller.play();
    }
    print('object 生命周期监听 didPop ${tabIndex}');
  }

  @override
  void didPopNext() {
    super.didPopNext();
    // 从其他页面pop回当前页面走这里
    if(tabIndex==1){
      _controller.play();
    }
    print('object 生命周期监听 didPopNext ${tabIndex}');
  }


  @override
  void dispose() {
    _controller.removeListener(listener);
    _controller.dispose();
    super.dispose();
    print('object 生命周期监听 dispose ${tabIndex}');
  }

}

// 功能
class FindFunWidget extends StatelessWidget {

  String name;

  String ic;

  FindFunWidget(this.name, this.ic);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 40.sp,
        margin: EdgeInsets.fromLTRB(0, 0, 0.w, 20.sp),
        alignment: Alignment.center,
        child: Column(
           children: [
              Container(
                 alignment: Alignment.center,
                 width: 40.sp,
                 height: 40.sp,
                 margin: EdgeInsets.fromLTRB(0, 0, 0, 10.sp),
                 decoration:BoxDecoration(shape:BoxShape.circle,color: Color(0x33000000) ) ,
                 child:Image.asset(assetPath(ic),width: 20.sp,height: 20.sp,color: Colors.white,),
              ),
              Text(name,textAlign: TextAlign.center,style: TextStyle(fontSize: 13.sp,color: Colors.white),),
           ],
        ),
    );
  }
}
